package com.srwl.mytx.widget;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.AddContactActivity;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.adapter.ContactListAdapter;
import com.srwl.mytx.adapter.WrapContentLinearLayoutManager;
import com.srwl.mytx.contrack.ContactContrack;
import com.srwl.mytx.contrack.ContactContrackImpl;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.ContactItem;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ContactListView_v1 extends LinearLayout implements ContactListAdapter.InteractionListener, ContactContrack.View {
    private static final String TAG = "ContactListView";
    public static final String DIALOG_ITEM_LOCATION = "查看定位";
    public static final String DIALOG_ITEM_TRACK = "查看轨迹";
    public static final String DIALOG_ITEM_RELATION = "无限互联";
    private static final String DIALOG_ITEM_PROFILE = "查看资料";
    private static final String DIALOG_ITEM_GROUP = "设置分组";
    private static final String DIALOG_ITEM_DELETE = "删除";
    private static final String DIALOG_ITEM_ADD_CONTACT = "重新添加";
    private static final String DIALOG_ITEM_AUTHORITY = "设置权限";
    private Context context;
    List<ContactItem> contactItems = new ArrayList<>();
    private ContactListAdapter contactListAdapter;
    private InteractionListener listener;
    private boolean updating;//更新中
    private ContactItem targetContactItem, dragContactItem;
    private ContactListAdapter.ViewHolder currentDragViewHold;
    private RecyclerView.ViewHolder lastTargetViewHolder;//上一次的目标对象
    private int startDragPosition;//开始拖拽时候的位置，一次拖拽中，该值是不变的
    private int currentTargetPosition;//不断的拖拽中，目标对象的位置是改变的
    private int currentDragItemPosition;//拖拽项的当前位置
    private ProgressDialog progressDialog;
    private ItemTouchHelper touchHelper;
    private RecyclerView rv_contact;
    private ContactContrack.Presenter presenter;

    public ContactListView_v1(@NonNull Context context) {
        super(context);
        this.context = context;

    }

    public ContactListView_v1(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;

    }

    public ContactListView_v1(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
    }


    public void init(List<Contact> contactList) {
        inflate(context, R.layout.contact_list_view, this);
        rv_contact = findViewById(R.id.rv_contact);
        generateContactItems(contactList);
        rv_contact.setLayoutManager(new WrapContentLinearLayoutManager(context, LinearLayout.VERTICAL, false));
        contactListAdapter = new ContactListAdapter(context, contactItems, this);
        rv_contact.setAdapter(contactListAdapter);
        initItemTouchHelper();
        rv_contact.setItemAnimator(new CustomItemAnimator());
        findViewById(R.id.iv_add_contact).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, AddContactActivity.class));
            }
        });

        setPresenter(new ContactContrackImpl(this, context));
    }

    private void initItemTouchHelper() {
        touchHelper = new ItemTouchHelper(new ItemTouchHelperCallBack());
        touchHelper.attachToRecyclerView(rv_contact);
//        if (touchHelper != null) {
//            touchHelper = null;
//        }
//        if (PreferenceManager.getInstance().getSettingContactGroup()) {
//        } else {
//            touchHelper = new ItemTouchHelper(new NoGroupModelItemTouchHelperCallBack());
//            touchHelper.attachToRecyclerView(ContactListView.this);
//        }
    }

    public void refresh(List<Contact> contactList) {
        generateContactItems(contactList);
        contactListAdapter.notifyDataSetChanged();
    }

    /**
     * 当联系人 分组模式 （是否分组显示）改变
     * 不知道在这个自定义view 里面注册广播后，却收不到
     */
    public void onContactGroupModelChange() {
        //刷新联系人 列表
        refresh(Helper.getInstance().getContactList());

        // initItemTouchHelper();
    }

    @NonNull
    private void generateContactItems(List<Contact> contactList) {
        contactItems.clear();
        if (Helper.getInstance().getModel().getSettingContactGroup()) {
            groupModel(contactList);
        } else {
            noGroupModel(contactList);
        }
    }

    /**
     * 联系人分组模式
     *
     * @param contactList
     */
    private void groupModel(List<Contact> contactList) {
        List<String> groupList = new ArrayList<>();

        for (Contact contact : contactList) {
            if (TextUtils.isEmpty(contact.getGroupName())) {
                contact.setGroupName("默认分组");
            }
            if (!groupList.contains(contact.getGroupName())) {
                groupList.add(contact.getGroupName());
            }
        }
        for (int x = 0; x < groupList.size(); x++) {
            String groupName = groupList.get(x);
            ContactItem parentItem = new ContactItem(ContactItem.CONTACT_ITEM_TYPE_PARENT, groupName);


//            for (Contact contact : contactList) {
//                if (TextUtils.equals(groupName, contact.getGroupName())) {
//                    ContactItem childItem = new ContactItem(ContactItem.CONTACT_ITEM_TYPE_CHILD);
//                    childItem.setContact(contact);
//                    //子项个父项互相持有
//                    childItem.setParentContact(parentItem);
//                    parentItem.getChildContactList().add(childItem);
//                }
//            }
            for (int y = 0; y < contactList.size(); y++) {
                Contact contact = contactList.get(y);
                if (TextUtils.equals(groupName, contact.getGroupName())) {
                    ContactItem childItem = new ContactItem(ContactItem.CONTACT_ITEM_TYPE_CHILD);
                    childItem.setContact(contact);
                    //子项与父项互相持有
                    childItem.setParentContact(parentItem);
                    parentItem.getChildContactList().add(childItem);
                }
                if (y == contactList.size() - 1) {
                    List<ContactItem> childContactList = parentItem.getChildContactList();
                    for (int i = 0; i < childContactList.size(); i++) {
                        int position1 = childContactList.get(i).getContact().getPosition();
                        for (int z = childContactList.size() - 1; z >= 0; z--) {
                            int position2 = childContactList.get(z).getContact().getPosition();
                            if (position2 < position1) {
                                childContactList.add(i, childContactList.remove(z));
                            }
                            if (i == z) {
                                break;
                            }
                        }
                    }
                }

            }

            contactItems.add(parentItem);
        }
    }

    /**
     * 联系人不分组
     *
     * @param contactList
     */
    private void noGroupModel(List<Contact> contactList) {

        for (int y = 0; y < contactList.size(); y++) {
            Contact contact = contactList.get(y);
            ContactItem childItem = new ContactItem(ContactItem.CONTACT_ITEM_TYPE_CHILD);
            childItem.setContact(contact);
            contactItems.add(childItem);
        }

        for (int i = 0; i < contactItems.size(); i++) {
            int position1 = contactItems.get(i).getContact().getPosition();
            for (int z = contactItems.size() - 1; z >= 0; z--) {
                int position2 = contactItems.get(z).getContact().getPosition();
                if (position2 < position1) {
                    contactItems.add(i, contactItems.remove(z));
                }
                if (i == z) {
                    break;
                }
            }
        }
    }


    @Override
    public void showMore(int position, ContactListAdapter.ViewHolder viewHolder) {
        currentDragViewHold = viewHolder;
        childViewGetMoreClick(position);
    }

    @Override
    public void addContact() {
        if (listener != null) {
            listener.addContact();
        }
    }

    @Override
    public void setPresenter(ContactContrack.Presenter presenter) {
        this.presenter = presenter;
    }

    /**
     * 分组模式下的  ItemTouchHelper
     */
    public class ItemTouchHelperCallBack extends ItemTouchHelper.Callback {


        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            if (updating) {//如果正在更新，不需要拖拽
                return ItemTouchHelper.ACTION_STATE_IDLE;
            }
            startDragPosition = viewHolder.getAdapterPosition();

            if (contactItems.get(startDragPosition).getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT) {//父item 不能被拖拽
                return ItemTouchHelper.ACTION_STATE_IDLE;
            }
            viewHolder.itemView.setBackgroundResource(R.drawable.drag_contact_item_background);//蓝色焦点边框
            currentDragViewHold = (ContactListAdapter.ViewHolder) viewHolder;
            ((ContactListAdapter.ViewHolder) viewHolder).divider.setVisibility(INVISIBLE);
            int dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.RIGHT;//ItemTouchHelper.ACTION_STATE_IDLE;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            int currentDragItemPosition = viewHolder.getAdapterPosition();
            int currentTargetPosition = target.getAdapterPosition();
            ContactItem dragContactItem = contactItems.get(currentDragItemPosition);
            ContactItem targetContactItem = contactItems.get(currentTargetPosition);
            //不是分组显示模式 或者分组模式下，目标位置不是0， 就交换位置
            if (!Helper.getInstance().getModel().getSettingContactGroup() || currentTargetPosition != 0) {
                replacePosition(currentDragItemPosition, currentTargetPosition, dragContactItem);
            }
            if (targetContactItem.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT) {
                //如果目标项是父项，并且没有展开，那就展开，

                if (currentDragItemPosition > currentTargetPosition && currentTargetPosition != 0) {//往上拖拽，判断再前面一项是否是父项，如果是并且没有展开子项，那就让它展开子项
                    ContactItem frontContactItem = contactItems.get(currentTargetPosition - 1);
                    if (frontContactItem.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT && !frontContactItem.isDisplayChildContact()) {
                        // replacePosition(currentDragItemPosition, currentTargetPosition, dragContactItem);//往上拖拽，遇到再前面一项也是父项，且未展开，应该先切换拖拽项与目标项的位置，再展开前面一项的子项
                        ContactListAdapter.ViewHolder frontViewHolder = (ContactListAdapter.ViewHolder) rv_contact.getChildViewHolder(getChildAt(currentTargetPosition - 1));
                        contactListAdapter.displayChildItem(frontContactItem, currentTargetPosition - 1, frontViewHolder, false);
//                        Handler handler = new Handler();
//                        handler.postDelayed(() -> contactListAdapter.displayChildItem(frontContactItem, currentTargetPosition - 1, frontViewHolder, false), 50);
                    }
                } else if (!targetContactItem.isDisplayChildContact()) {
                    contactListAdapter.displayChildItem(targetContactItem, currentTargetPosition, (ContactListAdapter.ViewHolder) target, false);
                    // Handler handler = new Handler();
                    //  handler.postDelayed(()-> replacePosition(currentDragItemPosition, currentTargetPosition, dragContactItem),50);
                }

                if (currentTargetPosition == 0) {//第一个，不能换位，
                    return false;
                } else {
                    //  replacePosition(currentDragItemPosition, currentTargetPosition, dragContactItem);
                }
            } else {//目标项是子项，不涉及 需要自动展开子项情况，直接切换拖拽项与目标项的位置
                //  replacePosition(currentDragItemPosition, currentTargetPosition, dragContactItem);
            }


            ContactListView_v1.this.currentDragItemPosition = currentDragItemPosition;
            ContactListView_v1.this.currentTargetPosition = currentTargetPosition;
            ContactListView_v1.this.dragContactItem = dragContactItem;
            ContactListView_v1.this.targetContactItem = targetContactItem;
//            contactListAdapter.notifyItemMoved(currentDragItemPosition, ContactListView.this.currentTargetPosition);
//            contactItems.remove(dragContactItem);
//            contactItems.add(currentTargetPosition, dragContactItem);

            //target.itemView.setBackgroundResource(R.drawable.target_contact_item_background);//灰色边框 想给在滑动的item 添加一个灰色边框，但是 没有找到合适的取消时机，
            return true;

        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            Log.d(TAG, "onSwiped: 滑动删除，，，，");
            final int position = viewHolder.getAdapterPosition();
            ContactItem contactItem = contactItems.get(position);
            Contact contact = contactItem.getContact();
            showDeleteContactDialog(position, contact);

        }


        @Override
        public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            Log.d(TAG, "clearView: 执行了");
            recoverBackground(viewHolder);
            recoverBackground(lastTargetViewHolder);
            //只拖着晃悠了下，，并没有切换行为产生
            if (targetContactItem == null) {
                return;
            }

            if (Helper.getInstance().getModel().getSettingContactGroup()) {

                if (targetContactItem.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT) {//目标对象是父项

                    handleTargetTypeIsPatent();
                } else {//目标对象是子项
                    handleTargetTypeIsChild();
                }
            } else {
                //因为在交换位置的时候，replacePosition（）， 拖拽项和目标项已经对调了，所以原始位置 fromPosition 是目标项现在的位置，toPosition是 拖拽项现在的位置
//                int toPosition = contactItems.indexOf(dragContactItem);
//                int fromPosition = contactItems.indexOf(targetContactItem);

//                int index;
//                if (currentDragItemPosition > currentTargetPosition) {//向上拖拽
//                    index = toPosition - 1;//插到目标项前面
//                } else {
//                    index = toPosition + 1;//向下拖拽，插到目标项下面
//                }
                if (dragContactItem.getContact().getPosition() == currentTargetPosition) {//如果被拽托的item 兜兜转转又回到原来的位置，那么直接return;
                    clear();
                    return;
                }
                refreshItemRange(startDragPosition, currentTargetPosition);

                // 更新原始位置和目标位置之间的全部Contact的位置信息到本地数据库，因为他们的位置都变了

                int startIndex = currentTargetPosition < startDragPosition ? currentTargetPosition : startDragPosition;
                int endIndex = currentTargetPosition > startDragPosition ? currentTargetPosition : startDragPosition;
                saveIndex(contactItems, startIndex, endIndex);

                clear();
            }
        }
    }

    void recoverBackground(RecyclerView.ViewHolder target) {
        if (target == null) {
            return;
        }
        TypedValue typedValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);
        target.itemView.setBackgroundResource(typedValue.resourceId);//恢复点击波纹效果的背景
        ((ContactListAdapter.ViewHolder) target).divider.setVisibility(VISIBLE);
    }

    /**
     * 移动item的位置
     *
     * @param fromPosition
     * @param toPosition
     * @param dragContactItem
     */
    private void replacePosition(int fromPosition, int toPosition, ContactItem dragContactItem) {
        contactListAdapter.notifyItemMoved(fromPosition, toPosition);
        contactItems.remove(dragContactItem);
        contactItems.add(toPosition, dragContactItem);
    }

    private void handleTargetTypeIsChild() {
        String fromGroupName = dragContactItem.getContact().getGroupName();
        String toGroupName = targetContactItem.getContact().getGroupName();
        if (TextUtils.equals(toGroupName, fromGroupName)) {//本组内位置更换

            //改变在父项中的位置
            ContactItem parentContactItem = targetContactItem.getParentContact();
            List<ContactItem> childContactList = parentContactItem.getChildContactList();
            int fromPosition = childContactList.indexOf(dragContactItem);
            int toPosition = childContactList.indexOf(targetContactItem);

            int index;
            if (currentDragItemPosition > currentTargetPosition) {//向上拖拽
                index = toPosition - 1;//插到目标项前面
            } else {
                index = toPosition + 1;//向下拖拽，插到目标项下面
            }
            if (dragContactItem.getContact().getPosition() == index) {//如果被拽托的item 兜兜转转又回到原来的位置，那么直接return;
                clear();
                return;
            }
            childContactList.add(toPosition, childContactList.remove(fromPosition));
            refreshItemRange(startDragPosition, currentTargetPosition);

            // 更新原始位置和目标位置之间的全部Contact的位置信息到本地数据库，因为他们的位置都变了

            int startIndex = toPosition < fromPosition ? toPosition : fromPosition;
            int endIndex = toPosition > fromPosition ? toPosition : fromPosition;
            saveIndex(childContactList, startIndex, endIndex);

            clear();
            return;
        }
        //如果在更新中，就不替换contactItemsCopy中的内容，用于更新失败的时候，恢复之前的分组信息

        updateGroupName(toGroupName, dragContactItem);
    }

    /**
     * 保存组内位置索引进数据库，这样当从数据库读取联系人信息的时候，才能排序
     *
     * @param childContactList
     * @param startIndex
     * @param endIndex
     */
    private void saveIndex(List<ContactItem> childContactList, int startIndex, int endIndex) {
        for (int i = startIndex; i <= endIndex; i++) {
            Contact contact = childContactList.get(i).getContact();
            contact.setPosition(i);
            contact.update();
        }
    }

    private void clear() {
        targetContactItem = null;//必须要清空
        dragContactItem = null;
        currentDragViewHold = null;
    }

    private void handleTargetTypeIsPatent() {

        if (currentDragItemPosition > currentTargetPosition) {//向上拖拽
            ContactItem frontContactItem = contactItems.get(currentTargetPosition - 1);//前一项
            //如果目标项的前面一项是拖拽项原本的父项，直接return
            if (dragContactItem.getParentContact() == frontContactItem) {
                clear();
                return;
            }
            if (frontContactItem.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT) {

                updateGroupName(frontContactItem.getGroupName(), dragContactItem);

            } else {
                updateGroupName(frontContactItem.getContact().getGroupName(), dragContactItem);
            }

        } else {
            //如果目标项是拖拽项原本的父项，当成组内换位处理
            if (dragContactItem.getParentContact() == targetContactItem) {

                //如果本来就是位于第一个，那么不做处理
                if (dragContactItem.getContact().getPosition() == 0) {
                    clear();
                    return;
                }
                //组内换位

                List<ContactItem> childContactList = targetContactItem.getChildContactList();
                int index = childContactList.indexOf(dragContactItem);
                childContactList.remove(dragContactItem);
                childContactList.add(0, dragContactItem);

                saveIndex(childContactList, 0, index);
                clear();
                return;
            }
            updateGroupName(targetContactItem.getGroupName(), dragContactItem);

        }
    }

    void showDeleteContactDialog(final int position, final Contact contact) {
        // 弹出对话  是否删除该好友
        User targetUser = contact.getTargetUser();
        if (targetUser == null) {
            Log.e(TAG, "showDeleteContactDialog: contact 中没有用户信息" + contact.toString());
            return;
        }
        ConfirmDialog dialog = new ConfirmDialog(context, "删除联系人", String.format("确定删除 %s 吗？  ", targetUser.getUsername()), true);

        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {

                //如果是临时联系人，不访问服务端，直接删除，因为服务端数据库Contact表并没有真实保存这个联系人
                if (contact.getType() != null && contact.getType() == Constant.CONTACT_TYPE_TEMP) {
                    onContactDelete(contact, position);
                } else {
                    deleteContact(contact, position);
                }
            }
        });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                notifyItemChanged(position);
            }
        });
        dialog.show();
    }

    void notifyItemChanged(int position) {
        contactListAdapter.notifyItemChanged(position);
    }

    /**
     * @param contact 我的好友
     */
    public void deleteContact(final Contact contact, final int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        //showProgressBar(true);
        final Contact updateContact = new Contact();
        updateContact.setcId(contact.getcId());
        String tId = contact.getTargetUser().getuId();
        updateContact.settId(tId);
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        body.put("ct", updateContact);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .deleteContact(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        //   showProgressBar(false);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(context.getString(R.string.system_busy));
                            notifyItemChanged(position);
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(context.getString(R.string.system_busy));
                            notifyItemChanged(position);
                            return;
                        }
                        //  showToast(getString(R.string.delete_contact_complete));
                        //  Helper.getInstance().deleteContact(contact);
                        onContactDelete(contact, position);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        // showProgressBar(false);
                        showToast(context.getString(R.string.system_busy));
                        notifyItemChanged(position);
                    }
                });
    }


    private void onContactDelete(Contact contact, int position) {
        String tId = contact.getTargetUser().getuId();
        DBManager.getInstance().getDaoSession().getContactDao().delete(contact);
        //删掉会话
        IMSClientBootstrap.getInstance().getConversationService().deleteConversation(contact.getTargetUser().getuId());
        //如果要在删除联系人的时候，删除对方相关的联系人通知消息，需要在 ContactConversation中写一个根据消息id 删除消息的方法；
        //IMSClientBootstrap.getInstance().getConversationService().getNotifyConversation(Constant.CONVERSATION_TYPE_CONTACT).deleteMessage();
        Helper.getInstance().refreshCache();
        ContactItem contactItem = contactItems.remove(position);
        contactListAdapter.notifyItemRemoved(position);
        ContactItem parentContact = contactItem.getParentContact();
        //如果是分组模式，需要根据 父Item 做进一步操作
        if (parentContact != null) {
            parentContact.getChildContactList().remove(contactItem);
            if (parentContact.getChildContactList().size() == 0) {//父item 中已经没有其他成员了，变成空的分组了，把父item 也去除掉
                contactItems.remove(position - 1);
                contactListAdapter.notifyItemRemoved(position - 1);
                if (position != contactItems.size()) {//从数据集中去除的不是最后两个的话，需要对后面的item 刷新
                    contactListAdapter.notifyItemRangeChanged(position - 1, contactItems.size() - (position - 1));
                }
            } else {
                if (position != contactItems.size()) {//只去除一个子item的情况，判断是否是最后一个，不是的话，需要对后面的item 刷新
                    contactListAdapter.notifyItemRangeChanged(position, contactItems.size() - position);
                }
            }
        }
        if (listener != null) {
            listener.onContactDelete();
        }
    }


    private void updateGroupName(final String newGroupName, ContactItem updateContactItem) {
        updating = true;
        Contact updateContact = new Contact();
        Contact contact = updateContactItem.getContact();
        updateContact.setcId(contact.getcId());
        //设置分组
        updateContact.setGroupName(newGroupName);
        currentDragViewHold.progressBar.setVisibility(VISIBLE);

        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        body.put("ct", updateContact);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .updateContact(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        currentDragViewHold.progressBar.setVisibility(INVISIBLE);
                        updating = false;
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(context.getString(R.string.system_busy));
                            if (dragContactItem != null && targetContactItem != null) {
                                recover();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(context.getString(R.string.system_busy));
                            if (dragContactItem != null && targetContactItem != null) {
                                recover();
                            }
                            return;
                        }
                        //  showToast(getString(R.string.update_complete));
                        Log.d(TAG, "onResponse: 更新分组信息完成");
                        onSetGroupInfoConplete(contact, newGroupName);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        currentDragViewHold.progressBar.setVisibility(INVISIBLE);
                        showToast(context.getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (dragContactItem != null && targetContactItem != null) {
                            recover();
                        }
                        updating = false;
                    }
                });
    }

    private void onSetGroupInfoConplete(Contact contact, String newGroupName) {
        contact.setGroupName(newGroupName);
        // Helper.getInstance().updateContact(contact);
        contact.update();
        Helper.getInstance().refreshCache();
        //非拖拽设置分组的情况，
        if (targetContactItem == null) {
            unDragChangeGroup(newGroupName);
            return;
        }
        changeDragItemInfo();
    }

    /**
     * 处理非拖拽更换分组的情况
     *
     * @param newGroupName
     */
    private void unDragChangeGroup(String newGroupName) {

        //  先查看新的分组名字是否是存在的
        for (int i = 0; i < contactItems.size(); i++) {
            ContactItem contactItem = contactItems.get(i);
            if (contactItem.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT && contactItem.getGroupName().equals(newGroupName)) {

                if (!contactItem.isDisplayChildContact()) {
                    ContactListAdapter.ViewHolder viewHolder = (ContactListAdapter.ViewHolder) rv_contact.getChildViewHolder(getChildAt(i));
                    contactListAdapter.displayChildItem(contactItem, i, viewHolder, true);
                }
                int toPosition = i;
                if (currentDragItemPosition > i) {//如果是向上换组，则插到目标父项的后面
                    toPosition = i + 1;
                }
                onUpdateGroupComplete(contactItem, toPosition);


                return;
            }
        }
        updateGroupOnCreateNewGroup(newGroupName);

    }

    /**
     * 通过对话框设置分组：移动设置项到新的分组下，重新设置分组从属信息
     *
     * @param parentContactItem
     * @param toPosition
     */
    private void onUpdateGroupComplete(ContactItem parentContactItem, int toPosition) {
        replacePosition(currentDragItemPosition, toPosition, dragContactItem);
        unbindWithOriginalParent();
        dragContactItem.setParentContact(parentContactItem);
        parentContactItem.getChildContactList().add(0, dragContactItem);
        refreshItemRange(currentDragItemPosition, toPosition);
    }

    /**
     * 通过对话框设置分组：设置了一个新分组
     *
     * @param newGroupName
     */
    private void updateGroupOnCreateNewGroup(String newGroupName) {
        ContactItem newParentContactItem = new ContactItem(ContactItem.CONTACT_ITEM_TYPE_PARENT, newGroupName);
        newParentContactItem.setDisplayChildContact(true);
        contactItems.add(newParentContactItem);
        int toPosition = contactItems.size() - 1;
        contactListAdapter.notifyItemInserted(toPosition);

        onUpdateGroupComplete(newParentContactItem, toPosition);
    }

    /**
     * 拖拽设置分组：服务端更新完成后，改变被拖拽的item的从属信息：
     */
    void changeDragItemInfo() {

        unbindWithOriginalParent();
        if (targetContactItem.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT) {//目标项是父项
            bindNewParentOnTargetTypeIsParent();
        } else {//目标项是子项
            bindNewParentOnTargetTypeIsChild();
        }
        dragContactItem = null;
        targetContactItem = null;

    }

    /**
     * 更新分组信息后，重新绑定新父项
     * 目标项是 子项
     */
    private void bindNewParentOnTargetTypeIsChild() {
        ContactItem parentContactItem = targetContactItem.getParentContact();
        List<ContactItem> childContactList = parentContactItem.getChildContactList();
        int toPosition = childContactList.indexOf(targetContactItem);//目标项在父项中的位置
        //以最后交换位置的两个item 判断拖拽方向
        if (currentDragItemPosition >= currentTargetPosition) {//向前拖拽
            childContactList.add(toPosition, dragContactItem);//把拖拽项添加进新的父项中,插入到目标对象的前面
        } else {
            childContactList.add(toPosition + 1, dragContactItem);//把拖拽项添加进新的父项中，插入到目标对象的后面
        }

        dragContactItem.setParentContact(targetContactItem.getParentContact());//拖拽项设置新的父项
        //跨组移动之后（更改分组之后），需要把移动过位置的所有item 刷新，不然position 是错位的，当展开子项的时候 会报错
        //以起始点判断 拖拽方向
        refreshItemRange(startDragPosition, currentTargetPosition);

    }

    /**
     * 更新分组信息后，重新绑定新父项
     * 目标项是  父项
     */
    private void bindNewParentOnTargetTypeIsParent() {
        if (currentDragItemPosition > currentTargetPosition) {//如果是向上拖拽，那么以再前面一项为参照项，加入它所在的分组
            ContactItem frontContactItem = contactItems.get(currentTargetPosition - 1);//前一项
            //与新的父项建立关系，互相持有
            ContactItem parentContact = frontContactItem.getParentContact();
            List<ContactItem> childContactList = parentContact.getChildContactList();
            childContactList.add(dragContactItem);//添加到子项列表的最后
            dragContactItem.setParentContact(parentContact);


        } else { //向下拖拽，目标项即为新的父项
            List<ContactItem> childContactList = targetContactItem.getChildContactList();
            childContactList.add(0, dragContactItem);//插入到新父项的第一个位置
            dragContactItem.setParentContact(targetContactItem);
        }
        refreshItemRange(startDragPosition, currentTargetPosition);
    }

    private void refreshItemRange(int startDragPosition, int currentTargetPosition) {
//        int positionStart = startDragPosition < currentTargetPosition ? startDragPosition : currentTargetPosition;
//        int itemCount = Math.abs(startDragPosition - currentTargetPosition);
//        contactListAdapter.notifyItemRangeChanged(positionStart, itemCount);

        contactListAdapter.notifyDataSetChanged();//全部刷新，，，
    }

    /**
     * 与原始父项解除绑定
     * 并判断父项的子项集合长度是否为0,
     * 如果为0，说明是光杆司令，去掉
     */
    private void unbindWithOriginalParent() {
        ContactItem originalParentContact = dragContactItem.getParentContact();
        originalParentContact.getChildContactList().remove(dragContactItem);//把自己从父项中移除
        if (originalParentContact.getChildContactList().size() == 0) {
            int index = contactItems.indexOf(originalParentContact);
            contactItems.remove(index);
            contactListAdapter.notifyItemRemoved(index);
            contactListAdapter.notifyItemRangeChanged(index, contactItems.size() - index);
        }
    }

    /**
     * 在更新分组失败的时候，根据拖拽最初的位置，进行逆向操作
     */
    private void recover() {
//        if (contactItemsCopy.size() != 0) {
//            contactItems.clear();
//            contactItems.addAll(contactItemsCopy);
//            dragContactItem.getParentContact().getChildContactList().clear();
//            dragContactItem.getParentContact().getChildContactList().addAll(fromContactItemsCopy);
//            if (targetContactItem.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT) {
//                targetContactItem.getChildContactList().clear();
//                targetContactItem.getChildContactList().addAll(toContactItemsCopy);
//            } else {
//                targetContactItem.getParentContact().getChildContactList().clear();
//                targetContactItem.getParentContact().getChildContactList().addAll(toContactItemsCopy);
//            }
//            contactListAdapter.notifyDataSetChanged();
//            contactItemsCopy.clear();
//            fromContactItemsCopy.clear();
//            toContactItemsCopy.clear();
//        }

        //更换显示界面中的位置
        replacePosition(currentTargetPosition, startDragPosition, dragContactItem);
        dragContactItem = null;
        targetContactItem = null;


    }

    private void childViewGetMoreClick(int position) {
        currentDragItemPosition = position;
        dragContactItem = contactItems.get(position);
        final Contact contact = dragContactItem.getContact();
        List<String> items = new ArrayList<>();
        items.add(DIALOG_ITEM_AUTHORITY);
        items.add(DIALOG_ITEM_PROFILE);
        items.add(DIALOG_ITEM_GROUP);
        items.add(DIALOG_ITEM_DELETE);

        String status = contact.getStatus();
        if ((status.equals(Constant.CONTACT_STATUS_ACTIVE_DELETE)) || (status.equals(Constant.CONTACT_STATUS_PASSIVE_DELETE))) {
            items.add(0, DIALOG_ITEM_ADD_CONTACT);
        } else {
            String loginUserID = UserProfileManager.getInstance().getLoginUserInfo().getuId();
//            User loginUserInfo = Helper.getInstance().getUserProfileManager().getLoginUserInfo();
            //判断当前登录的用户是否为主动添加方,就使用lcation判断对方是否给我权限
            if (TextUtils.equals(loginUserID, contact.getmId())) {
                if (TextUtils.equals(contact.getLocation(), Constant.CONTACT_HAVE_AUTHORITY)) {
                    items.add(0, DIALOG_ITEM_LOCATION);
                }
            } else {
                //如果不是主动添加方,那么就是被动添加方,就使用t_location判断对方是否给我权限
                if (TextUtils.equals(contact.getTLocation(), Constant.CONTACT_HAVE_AUTHORITY)) {
                    items.add(0, DIALOG_ITEM_LOCATION);
                }
            }

            if (TextUtils.equals(contact.getTrace(), Constant.CONTACT_HAVE_AUTHORITY)) {
                items.add(0, DIALOG_ITEM_TRACK);
            }
            //判断当前登录用户给是否为主动添加方,就使用relationInfinite判断对方是否给我权限
            if (TextUtils.equals(loginUserID, contact.getmId())) {
                if (TextUtils.equals(contact.getRelationInfinite(), Constant.CONTACT_HAVE_AUTHORITY)) {
                    items.add(0, DIALOG_ITEM_RELATION);

                }
            } else {
                //如果不是主动添加方,就直接使用tRelationInfinite判断对方是否给我权限
                if (TextUtils.equals(contact.getTRelationInfinite(), Constant.CONTACT_HAVE_AUTHORITY)) {
                    items.add(0, DIALOG_ITEM_RELATION);

                }
            }
        }


        BottomDialog bottomDialog = new BottomDialog(context, items);
        bottomDialog.show();
        bottomDialog.setListener(generateListener(position, contact));

    }

    private BottomDialog.InteractionListener generateListener(final int itemPosition, final Contact contact) {
        final User targetUser = contact.getTargetUser();
        return new BottomDialog.InteractionListener() {
            @Override
            public void onDialogItemViewClick(int position, String itemName) {
                switch (itemName) {
                    case DIALOG_ITEM_LOCATION:
//                        if (mMarker != null) {
//                            mBaiduMap.clear();
//                            mMarker = null;
//                        }

                        Contact targetContact = new Contact();
                        //携带对方联系人ID
                        targetContact.setcId(contact.getcId());
                        targetContact.settId(contact.gettId());
                        JSONObject body = new JSONObject();
                        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
                        body.put("ct", targetContact);
                        getLocation(body);

                        break;
                    case DIALOG_ITEM_TRACK:


                        break;
                    case DIALOG_ITEM_PROFILE:
                        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));

                        break;
                    case DIALOG_ITEM_ADD_CONTACT:
                        presenter.addContact(contact, context.getString(R.string.default_invite_message));
                        break;
                    case DIALOG_ITEM_DELETE:
                        showDeleteContactDialog(itemPosition, contact);

                        break;
                    case DIALOG_ITEM_AUTHORITY:
                        showAuthorityDialog(contact, targetUser);
                        break;
                    case DIALOG_ITEM_GROUP:
                        //先判断是否是分组模式，分组模式才显示分组的设置
                        if (!Helper.getInstance().getModel().getSettingContactGroup()) {
                            ConfirmDialog dialog = new ConfirmDialog(context, "提示", "当前非分组模式，设置分组信息需要先切换至分组显示模式，切换模式？", true);
                            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                                @Override
                                public void confirm() {
                                    Helper.getInstance().getModel().setSettingContactGroup(true);
                                    onContactGroupModelChange();
                                }
                            });
                            dialog.show();

                            return;
                        }

                        GroupDialog groupDialog = new GroupDialog(getContext(), contact);
                        groupDialog.setListener(new GroupDialog.InteractionListener() {
                            @Override
                            public void onComplete(final String newGroupName) {
                                //如果是零时联系人，直接修改，不用访问服务端
                                if (contact.getType() != null && contact.getType() == Constant.CONTACT_TYPE_TEMP) {
                                    onSetGroupInfoConplete(contact, newGroupName);
                                } else {
                                    updateGroupName(newGroupName, dragContactItem);
                                }
                            }
                        });
                        groupDialog.show();
                        break;
                    case DIALOG_ITEM_RELATION:

                        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "暂未开放");
                        dialog.show();

//                        InfiniteConnect infiniteConnect = contact.getInfinite().get(0);
//                        String connectKey = infiniteConnect.getConnectKey();


//                        ArrayList<Contact> contactArrayList = new ArrayList<>();
//                        contactArrayList.add(contact);
//                        ConnectInfiniteDialog connectInfiniteDialog = ConnectInfiniteDialog.getInstance(contactArrayList, "实人部落");
//                        connectInfiniteDialog.show(((FragmentActivity) context).getSupportFragmentManager(), "MmapFragment");//getFragmentManager()
                        break;
                }
            }
        };
    }

    private void getLocation(JSONObject body) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        showProgressBar("正在请求对方位置信息...");
        RetrofitManager.getInstance().createRequest(UserService.class)
                .location(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideProgressBar();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(context.getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            switch (result.getStatus()) {
                                case Constant.NO_AUTHORITY:
                                    showToast(context.getString(R.string.lock_of_authority));
                                    return;
                            }
                        }
                        showToast("请求已经完成，等待查询结果");

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        hideProgressBar();
                        showToast(context.getString(R.string.system_busy));
                    }
                });
    }

    void showAuthorityDialog(final Contact contact, final User targetUser) {
        final AuthorityDialog authorityDialog = new AuthorityDialog(getContext(), contact);
        authorityDialog.setListener(new AuthorityDialog.InteractionListener() {
            @Override
            public void onConfirm(final Contact updateContact) {

                showProgressBar("正在更新权限...");
                //把在后端需要的几个数据补上：1、自己的contact ID
                updateContact.setcId(contact.getcId());
                updateContact.setmId(contact.getmId());
                //判断当前登录的用户是否为主动添加方
                String loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
                if (TextUtils.equals(loginUserId, contact.getmId())) {
                    //如果是主动添加方,那么将location,relationInfinite返回给服务器端
                    updateContact.setLocation(contact.getLocation());
                    updateContact.setRelationInfinite(contact.getRelationInfinite());
                } else {
                    //如果是被动添加方,那么将tLocation,tRelationInfineite返回给服务器端
                    updateContact.setTLocation(contact.getTLocation());
                    updateContact.setTRelationInfinite(contact.getTRelationInfinite());
                }
                //设置对方user ID,这个用来发送通知给对方,并将对方给我的权限信息设置进来
                updateContact.settId(targetUser.getuId());

                //判断是否是临时联系人，这条联系人在后端数据库并不存在，直接按设置结果保存
                if (contact.getType() != null && contact.getType() == Constant.CONTACT_TYPE_TEMP) {
                    onContactAuthorityChange(updateContact, contact);
                    hideProgressBar();
                    authorityDialog.dismiss();
                    showToast(context.getString(R.string.set_authority_complete));
                    return;
                }
                RetrofitManager.getInstance()
                        .createRequest(UserService.class)
                        .updateContact(updateContact)
                        .enqueue(new Callback<CommonResult>() {
                            @Override
                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                hideProgressBar();
                                CommonResult result = response.body();
                                if (!response.isSuccessful() || result == null) {
                                    Log.e(TAG, "onResponse: " + response.message());
                                    showToast(context.getString(R.string.system_busy));
                                    return;
                                }
                                if (result.isError()) {
                                    Log.e(TAG, "onResponse: " + result.getMsg());
                                    showToast(context.getString(R.string.system_busy));
                                    return;
                                }

                                authorityDialog.dismiss();
                                showToast(context.getString(R.string.set_authority_complete));

                                // Helper.getInstance().updateContact(contact);
                                // contact.update();

                                onContactAuthorityChange(updateContact, contact);
                            }

                            @Override
                            public void onFailure(Call<CommonResult> call, Throwable t) {
                                hideProgressBar();
                                showToast(context.getString(R.string.system_busy));

                            }
                        });


            }
        });
        authorityDialog.show();
    }

    private void onContactAuthorityChange(Contact updateContact, Contact contact) {
        if (updateContact.getTTrace() != null) {
            contact.setTTrace(updateContact.getTTrace());
        }
        //需要更新定位权限
        if (updateContact.getTLocation() != null) {
            contact.setTLocation(updateContact.getTLocation());
        }
        if (updateContact.getLocation() != null) {
            contact.setLocation(updateContact.getLocation());
        }
        //需要更新亲戚互联权限
        if (updateContact.getTRelationInfinite() != null) {
            contact.setTRelationInfinite(updateContact.getTRelationInfinite());
        }
        if (updateContact.getRelationInfinite() != null) {
            contact.setRelationInfinite(updateContact.getRelationInfinite());
        }
        if (updateContact.getInfiniteKey() != null) {
            contact.setInfiniteKey(updateContact.getInfiniteKey());
        }
        if (updateContact.getInfiniteTag() != null) {
            contact.setInfiniteTag(updateContact.getInfiniteTag());
        }
        if (updateContact.getInfiniteChat() != null) {
            contact.setInfiniteChat(updateContact.getInfiniteChat());
        }
        if (updateContact.getUpChat() != null) {
            contact.setUpChat(updateContact.getUpChat());
        }
        if (updateContact.getAdjustStructure() != null) {
            contact.setAdjustStructure(updateContact.getAdjustStructure());
        }
        //DBManager.getInstance().getDaoSession().getContactDao().update(contact);
        contact.update();
        Helper.getInstance().refreshCache();
        //refreshVideoItem();
    }


    public void showToast(String content) {
        Snackbar.make(this, content, Snackbar.LENGTH_LONG).show();
    }

    private void showProgressBar(String msg) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(context);
        }
        progressDialog.setMessage(msg);
        progressDialog.show();
    }

    private void hideProgressBar() {
        if (progressDialog == null) {
            return;
        }
        progressDialog.dismiss();
    }

    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {
        void onContactDelete();
        void addContact();
    }


    class CustomItemAnimator extends DefaultItemAnimator {
        @Override
        public void endAnimation(RecyclerView.ViewHolder item) {
            super.endAnimation(item);

        }


        @Override
        public void onMoveStarting(RecyclerView.ViewHolder item) {
            super.onMoveStarting(item);
            if (item != currentDragViewHold) {
                item.itemView.setBackgroundResource(R.drawable.target_contact_item_background);//目标项动画执行过程中，设置灰色边框，一直维持到下一个目标项动画结束
            }
        }

        @Override
        public void onMoveFinished(RecyclerView.ViewHolder item) {
            super.onMoveFinished(item);
            if (currentDragViewHold == null || item != currentDragViewHold) {

                if (currentDragItemPosition > currentTargetPosition) {
                    recoverBackground(lastTargetViewHolder);//本次动画结束，清除上一移动项的边框
                } else {
                    recoverBackground(item);//清除本item的边框
                }
                lastTargetViewHolder = item;
            }
        }
    }
}
